package com.huayue.service;

import java.math.BigDecimal;
import java.util.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.huayue.dao.*;
import com.huayue.entity.CheckOut;
import com.huayue.entity.RoomPredictOrder;
import com.huayue.entity.RoomStatus;
import com.huayue.entity.User;
import com.huayue.util.DateHelper;

/**
 * 退房
 */
@Service
public class RoomCheckOutService extends BaseService<RoomPredictOrder> {

    @Autowired
    RoomCheckOutDao dao;

    @Autowired
    RoomStatusDao rsdao;

    @Autowired
    RoomRealOrderDetailsDao rrodDao;

    @Override
    public BaseDao<RoomPredictOrder> getDao() {

        /**
         * "product": [{ "type": "房费", "date": "2020-3-4", "price": 80, "number": 1, "allprice": 80 }, { "type": "可乐",
         * "productId": "1", "date": "2020-3-4", "price": 3.5, "number": 2, "allprice": 7 }, { "type": "泡面",
         * "productId": "2", "date": "2020-3-4", "price": 5, "number": 2, "allprice": 10 }]
         */
        return dao;
    }

    public Map<String, Object> findRealOrderByRoomId(Integer id) {
        // 查询预付款
        // 获取到roomName，roomType，real_in_date，cname，predictMoney，deposit
        Map<String, Object> info = dao.findRoomPredictOrderByRoomId(id);
        // 实际入店日期
        Date oldInDate = DateHelper.StringToDate(info.get("real_in_date").toString());
        // 预计离店日期
        Date oldOutDate = DateHelper.StringToDate(info.get("real_out_date").toString());
        // 房价
        BigDecimal price = new BigDecimal(info.get("predictMoney").toString());
        // 原天数
        int num = DateHelper.getDateRangeNumber(DateHelper.StringToDate(info.get("intime").toString()),
            DateHelper.StringToDate(info.get("outtime").toString()));
        // int num = Integer.valueOf(info.get("days").toString());
        // 新天数
        int num2 = DateHelper.getDateRangeNumber(oldInDate, new Date());
        // 判断不到一天的按一天算，超过一天的超过中午12点加一天
        if (num2 == 0) {
            num2 = 1;
        } else {
            Calendar cale = Calendar.getInstance();
            cale.setTime(new Date());
            if (cale.get(Calendar.HOUR_OF_DAY) > 12) {
                num2 += 1;
            }
        }

        // 已预付金额
        BigDecimal predictMoney = findPredictPriceByRoomId(id);
        // 计算预付金额
        info.put("predictMoney", predictMoney);
        // 真实住店天数
        info.put("RealDays", num2);
        // 实际入住时间
        info.put("real_in_date", DateHelper.DateToString(DateHelper.StringToDate(info.get("real_in_date").toString())));
        // 实际离开时间
        info.put("real_out_date", DateHelper.DateToString(new Date()));
        // 真实消费金额
        BigDecimal RealExpMoney = new BigDecimal("0");
        // 房间/换房信息
        List<Map<String, Object>> products = dao.findPredictOrderDetailsByRoomIdAndOrder(info.get("id").toString(), id);
        List<Map<String, Object>> returnInfo = new ArrayList<Map<String, Object>>();
        for (int i = 0; i < products.size(); i++) {
            Map<String, Object> room = new HashMap<String, Object>();
            room.put("rid", products.get(i).get("id"));
            room.put("type", products.get(i).get("name") + "房费");
            // 房间实际价格
            BigDecimal onePrice = new BigDecimal(products.get(i).get("price").toString());
            room.put("price", onePrice);
            // 计算实际天数
            int number =
                DateHelper.getDateRangeNumber(DateHelper.StringToDate(products.get(i).get("crdate").toString()),
                    DateHelper.StringToDate(products.get(i).get("chdate").toString()));
            // 日期数据
            room.put("date", products.get(i).get("crdate").toString());
            // 判断若时间不足一天则改为一天，避免不收费
            if (products.get(i).get("name").toString().equals(info.get("roomName").toString())) {
                number = DateHelper
                    .getDateRangeNumber(DateHelper.StringToDate(products.get(i).get("crdate").toString()), new Date());
                Calendar cal = Calendar.getInstance();
                cal.setTime(new Date());

                if (cal.get(Calendar.HOUR_OF_DAY) > 12) {
                    number += 1;
                }
                if (number == 0) {
                    number = 1;
                }
            }
            room.put("number", number);
            BigDecimal allPrice = onePrice.multiply(new BigDecimal(number));
            // 实际消费金额
            room.put("allprice", allPrice);
            // 将每间房间实际花费添加至实际花费金额中
            RealExpMoney = RealExpMoney.add(allPrice);
            returnInfo.add(room);
        }
        // 金额差
        if (predictMoney.compareTo(RealExpMoney) == 0) {
            // 天数正常
            info.put("orderType", "正常");
            info.put("amount", 0);
        } else if (predictMoney.compareTo(RealExpMoney) == -1) {
            // 房间晚退，补缴房费
            info.put("orderType", "需补缴");
            BigDecimal totalPrice = RealExpMoney.subtract(predictMoney);
            info.put("amount", totalPrice);
        } else if (predictMoney.compareTo(RealExpMoney) == 1) {
            // 提前结算，退房费
            info.put("orderType", "退款");

            BigDecimal totalPrice = predictMoney.subtract(RealExpMoney);
            info.put("amount", totalPrice);
        }
        info.put("products", returnInfo);
        return info;
    }

    public boolean checkOut(CheckOut checkOut, User user) {
        boolean payStatus = false;
        if ("需补缴".equals(checkOut.getOrderType())) {
            // 1.查验需要补缴的费用是否支付成功
            if (checkOut.getAmount().compareTo(new BigDecimal("0")) != 0) {
                if (checkOut.getPayType() == 0) {
                    AliPayDao aliPayDao = new AliPayDao();
                    int i = aliPayDao.findPayByOrderNumber(checkOut.getDepOrderNumber()).size();
                    if (i == 1) {
                        payStatus = true;
                    } else {
                        // 未付款
                        payStatus = false;
                    }
                }
                payStatus = true;
            } else {
                payStatus = true;
            }
        } else if ("退款".equals(checkOut.getOrderType())) {
            // 入住订单详情用预付金额减去退款金额
            int i = dao.updateRealDetails(checkOut.getRoomId(), checkOut.getAmount());
            if (i == 1) {
                payStatus = true;
            } else {
                // 未付款
                payStatus = false;
            }
        } else if ("正常".equals(checkOut.getOrderType())) {
            payStatus = true;
        }
        // 金额不通过直接退出
        if (!payStatus) {
            return false;
        }
        // 2.退还押金
        int i = dao.updateDeposit(checkOut.getRoomId(), user.getId());
        if (i == 1) {
            // 3.改房态
            RoomStatus roomStatus = new RoomStatus();
            roomStatus.setRoomId(Long.valueOf(checkOut.getRoomId()));
            roomStatus.setStatusId(Long.valueOf(4));
            int s = rsdao.updateStatusByRoomId(roomStatus);
            // 修改当前订单的状态未已完成
            updateRealDetailsStatus9(checkOut.getRoomId());
            // 将与该房间绑定的所有用户取消关联
            dao.updateCustomerRoomId(checkOut.getRoomId());
            // System.out.println(products);
            // 房态修改成功，退房流程结束
            if (s == 1) {
                return true;
            }
        }
        return false;
    }

    /**
     * 根据房间id查询预付款
     *
     * @return
     */
    public BigDecimal findPredictPriceByRoomId(Integer roomId) {
        return dao.findPredictPriceByRoomId(roomId);
    }

    public int updateRealDetailsStatus9(Integer roomID) {
        return rrodDao.updateRealDetailsStatus9(roomID);
    }
}
